package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.Order;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.amqp.IotMsgBody;
import com.zzyl.nursing.amqp.IotMsgNotifyData;
import com.zzyl.nursing.amqp.IotMsgService;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * cxlService业务层处理
 *
 * @author cxl
 * @date 2025-10-28
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询cxl
     *
     * @param id cxl主键
     * @return cxl
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询列表
     *
     * @param
     * @return cxl
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto) {
        Page<DeviceData> page = Page.of(dto.getPageNum(), dto.getPageSize());
        page.addOrder(OrderItem.desc("alarm_time"));
        lambdaQuery()
                .eq(StrUtil.isNotEmpty(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .eq(DeviceData::getFunctionId, dto.getFunctionId())
                .ge(Objects.nonNull(dto.getStartTime()), DeviceData::getAlarmTime, dto.getStartTime())
                .le(Objects.nonNull(dto.getEndTime()), DeviceData::getAlarmTime, dto.getEndTime())
                .page(page);
        //
        return new TableDataInfo<DeviceData>(page.getTotal(), page.getRecords(), HttpStatus.SUCCESS, "查询成功");
    }

    /**
     * 新增cxl
     *
     * @param deviceData cxl
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改cxl
     *
     * @param deviceData cxl
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除cxl
     *
     * @param ids 需要删除的cxl主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除cxl信息
     *
     * @param id cxl主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从iot平台上存消息队列到数据库
     *
     * @param iotMsgNotifyData
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //1.获取设备上的数据
        IotMsgBody body = iotMsgNotifyData.getBody();
        if (Objects.nonNull(body)) {
            //消息内容中的模型数据
            List<IotMsgService> services = body.getServices();
            if (CollUtil.isNotEmpty(services)) {
                //解析header中的设备id在数据库中是否存在
                String iotId = iotMsgNotifyData.getHeader().getDeviceId();
                Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
                List<DeviceData> deviceDataList = new ArrayList<>();
                if (null != device) {
                    //存在设备
                    services.forEach(service -> {
                        String eventTimeStr = service.getEventTime();
                        LocalDateTime eventTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
                        //日期时区转换
                        LocalDateTime eventTime8 = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                                .toLocalDateTime();
                        Map<String, Object> map = service.getProperties();
                        map.forEach((k, v) -> {
                            DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                            //剔除创建时间、修改时间、id、更新者、创建者
                            deviceData.setId(null);
                            deviceData.setCreateTime(null);
                            deviceData.setUpdateTime(null);
                            deviceData.setCreateBy(null);
                            deviceData.setUpdateBy(null);

                            //functionId
                            deviceData.setFunctionId(k);
                            //dataValue
                            deviceData.setDataValue(String.valueOf(v));
                            //alarmTime
                            deviceData.setAlarmTime(eventTime8);
                            //
                            deviceDataList.add(deviceData);
                        });
                    });
                }
                //是否存在要保存的数据
                if (CollUtil.isNotEmpty(deviceDataList)) {
                    //批量保存
                    saveBatch(deviceDataList);
                    //存入redis
                    redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, iotId, JSONUtil.toJsonStr(deviceDataList));

                }
            }
        }
    }
}
